package com.uchedao.vehicledetection.view.condition;

import android.content.ContentValues;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.adapter.EngineManualAdapter;
import com.uchedao.vehicledetection.adapter.EngineManualAdapter.EngineManualAdapterListener;
import com.uchedao.vehicledetection.db.DbHelper;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.loadstate.UCheDaoRelativeLayout;
import com.uchedao.vehicledetection.model.Condition;
import com.uchedao.vehicledetection.model.Detection;
import com.uchedao.vehicledetection.model.Draft;
import com.uchedao.vehicledetection.model.ResultInt;
import com.uchedao.vehicledetection.view.widget.stickylistheaders.StickyListHeadersListView;

import java.util.ArrayList;

;

/**
 * Description:工况检测view
 * <p/>
 * Date: 2015-09-16  10:07
 * User: wushan
 */
public class ConditionOutFunctionView extends UCheDaoRelativeLayout {


    private Condition condition;

    public ConditionOutFunctionView(Context context) {
        super(context);
    }

    public ConditionOutFunctionView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ConditionOutFunctionView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean save() {

        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(condition));

        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);

        // 若VIN值为空
        if (TextUtils.isEmpty(condition.config_info.vin))
            condition.config_info.vin = GlobalInfo.draft.car_vin;

            // 如果VIN值有更改
        else if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
        }

        // int status = GlobalInfo.draft.status[Draft.TYPE_CONDITION];
        // // 若原先状态为未完成，且数据已变动，则状态改变为已完成
        // if (GlobalInfo.draft.status[Draft.TYPE_CONDITION] !=
        // Draft.STATUE_FINISH) {
        // values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, Draft.STATUE_FINISH);
        // status = Draft.STATUE_FINISH;
        // }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values)) {
            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));
            return true;
        }

        return false;
    }

    @Override
    public boolean dataChanged() {
//        L.i(toJson(condition));
//        L.i(toJson(GlobalInfo.draft.condition));
        return !toJson(condition).equals(toJson(GlobalInfo.draft.condition));
//        return false;
    }

    @Override
    public void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.view_detection, this);
        StickyListHeadersListView stickListHeadersListView = (StickyListHeadersListView) findViewById(R.id.detection_listView);

        stickListHeadersListView.addFooterView(LayoutInflater.from(mContext).inflate(R.layout.view_condition_performance, null));
        EngineManualAdapter adapter = new EngineManualAdapter(mContext, getOutFunctionData(),
                new EngineManualAdapterListener() {

                    @Override
                    public void onResult(int position, ArrayList<Integer> value) {

                    }

                    @Override
                    public void onResult(int position, int value) {
                        condition.function.external_lighting[position].result = value;
                    }

                    @Override
                    public void onResult(int position, String value) {

                    }
                });
        stickListHeadersListView.setAdapter(adapter);
        // 左前轮
        initOutFunctionLayoutTire(R.id.LF_tire_input_tip_iv, R.id.LF_tire_result_et, R.id.LF_tire_result_tv,
                condition.function.left_front);
        // 左后轮
        initOutFunctionLayoutTire(R.id.LB_tire_input_tip_iv, R.id.LB_tire_result_et, R.id.LB_tire_result_tv,
                condition.function.left_rear);
        // 右前轮
        initOutFunctionLayoutTire(R.id.RF_tire_input_tip_iv, R.id.RF_tire_result_et, R.id.RF_tire_result_tv,
                condition.function.right_front);
        // 右后 轮
        initOutFunctionLayoutTire(R.id.RB_tire_input_tip_iv, R.id.RB_tire_result_et, R.id.RB_tire_result_tv,
                condition.function.right_rear);
    }

    @Override
    public void initDataBeforView() {
//        if (GlobalInfo.draft == null) {
//            GlobalInfo.draft = new Draft();
//        }
        condition = GlobalInfo.draft.condition.clone();
    }

    @Override
    public void initDataAfterView() {

    }

    @Override
    public void initListener() {

    }

    private ArrayList<Detection> getOutFunctionData() {

        ArrayList<Detection> array = new ArrayList<Detection>();
        String header1 = GlobalInfo.resources.getString(R.string.out_light_check_parts);
        // String header2 = GlobalInfo.resources
        // .getString(R.string.tire_check_parts);
        String[] texts = GlobalInfo.resources.getStringArray(R.array.out_function_values);
        Detection detection = null;

        int i = 0;
        for (; i < 7; i++) {
            if (condition.function.external_lighting[i] == null) {
                condition.function.external_lighting[i] = new ResultInt();
                condition.function.external_lighting[i].name = texts[i];
            }
            detection = new Detection(Detection.TYPE_THREE_SELECT);
            detection.setHeader(header1);
            detection.setText(texts[i]);
            detection.setRequestFocus(true);
            detection.setResId(R.array.funciton_three_select_values);
            detection.setValue(condition.function.external_lighting[i].result);
            array.add(detection);
        }
        // for (; i < texts.length; i++) {
        // detection = new Detection(Detection.TYPE_INPUT);
        // detection.setHeader(header2);
        // detection.setText(texts[i]);
        // detection.setRequestFocus(false);
        // detection.setResId(R.array.funciton_two_select_values);
        // detection.setKey(getString(R.string.tire_attrition_unit));
        // array.add(detection);
        // }

        return array;
    }

    /**
     * 轮胎磨损极限 初始化
     *
     * @param imgId
     * @param editId
     * @param resultId
     * @param etValue
     */
    private void initOutFunctionLayoutTire(int imgId, int editId, final int resultId, String etValue) {
        final String[] values = GlobalInfo.resources.getStringArray(R.array.funciton_two_select_values);
        final ImageView iv = (ImageView) findViewById(imgId);
        EditText et = (EditText) findViewById(editId);
        final TextView tv = (TextView) findViewById(resultId);

        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();

                switch (resultId) {
                    case R.id.LF_tire_result_tv:
                        condition.function.left_front = s.toString();
                        // condition.function.left_front =
                        // Float.parseFloat(s.toString());
                        break;

                    case R.id.LB_tire_result_tv:
                        condition.function.left_rear = s.toString();
                        // condition.function.left_rear =
                        // Float.parseFloat(s.toString());
                        break;

                    case R.id.RF_tire_result_tv:
                        condition.function.right_front = s.toString();
                        // condition.function.right_front =
                        // Float.parseFloat(s.toString());
                        break;

                    case R.id.RB_tire_result_tv:
                        condition.function.right_rear = s.toString();
                        // condition.function.right_rear =
                        // Float.parseFloat(s.toString());
                        break;
                }

                if (TextUtils.isEmpty(temp)) {
                    iv.setVisibility(View.VISIBLE);
                } else {
                    iv.setVisibility(View.INVISIBLE);
                }
                try {
                    float k = Float.parseFloat(temp);
                    if (k <= 1.65) {
                        tv.setText(values[1]);
                        tv.setBackgroundResource(R.color.deep_red);
                        tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0, 0, 0);
                        return;
                    }
                } catch (NumberFormatException e) {
                }
                tv.setText(values[0]);
                tv.setBackgroundResource(R.color.deep_green);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0, 0, 0);

                int posDot = temp.indexOf(".");
                if (posDot <= 0) {
                    return;
                }
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }

            }
        });
        et.setText(etValue);
    }
}
